package org.lewis.core.mvc.view;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolManager;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.view.ServletUtils;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.servlet.view.velocity.VelocityToolboxView;

public class LewisVelocityToolBoxView extends VelocityToolboxView {
	
	public LewisVelocityToolBoxView(){
		super();
	}

	@Override
	protected Context createVelocityContext(
			Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ViewToolContext velocityContext = new ViewToolContext(getVelocityEngine(), request, response, getServletContext());
		velocityContext.putAll(model);
		if (getToolboxConfigLocation() != null) {
			ToolManager toolManager = new ToolManager();
			toolManager.setVelocityEngine(velocityContext.getVelocityEngine());
			toolManager.configure(ServletUtils.getConfiguration(getToolboxConfigLocation(), getServletContext()));
			ToolboxFactory toolboxFactory=toolManager.getToolboxFactory();
			if (toolboxFactory.hasTools(Scope.REQUEST)) {
				velocityContext.addToolbox(toolboxFactory.createToolbox(Scope.REQUEST));
            }
			if (toolboxFactory.hasTools(Scope.APPLICATION)) {
				velocityContext.addToolbox(toolboxFactory.createToolbox(Scope.APPLICATION));
            }
			if (toolboxFactory.hasTools(Scope.SESSION)) {
				velocityContext.addToolbox(toolboxFactory.createToolbox(Scope.SESSION));
            }
		}
		return velocityContext;
	}

}
